#!/usr/bin/env python 3.6
# -*- coding: utf-8 -*-
# @Time      :2019/4/10
# @Author    :Tian Maohong
# @Email     :tianmaohong@bbdservice.com
# @File      :R30_EC_UpaidBusinessBadCheck
# @Software  :PyCharm


'''eof
name:申请企业未结清业务五级分类校验（不良类）
code:R30_EC_UpaidBusinessBadCheck_2D
tableName:
columnName:
groups:企业征信校验
dependencies:EC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import re
import sys
import datetime


reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def formatData(table_Name):
    """
    获取数据
    :param table_Name:字典keys
    :return:[{}]
    """
    try:
        data = EC_DSJ_2D["data"].get(table_Name)
        # table 不存在
        if data is None:
            return None
        # 表存在 但是为空[]
        elif (isinstance(data, list) and len(data) == 0) or data == "":
            return [{}]
        else:
            return data
    except:
        return None

def isFloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """

    return_data = None
    data_value = str(data_value)
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        r = re.compile(r'\D+')
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y.%m.%d').strftime('%Y-%m-%d')
        except:
            try:
                return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d').strftime('%Y-%m-%d')
            except:
                try:
                    return_data = datetime.datetime.strptime(data_value, '%Y/%m/%d').strftime('%Y-%m-%d')
                except:
                    try:
                        data_value = r.sub('', data_value)
                        return_data = datetime.datetime.strptime(data_value, '%Y%m%d').strftime('%Y-%m-%d')
                    except:
                        return_data = None

    return return_data



# Factor1
def factor1(EBB):
    if EBB in null_type_list:
        return None
    elif EBB == [{}]:
        return 0
    else:
        Factor1 = 0
        #借贷交易汇总信息单元  EB02  [0..1]
        EB02 = EBB[0].get("EB02")
        if EB02 is None:
            return 0
        elif EB02 in null_type_list:
            return None
        else:
            # 未结清借贷交易汇总信息段  EB02A  [1..1]
            EB02A = EB02[0].get("EB02A")
            if EB02A in null_type_list:
                return None
            else:
                EB02AH = EB02A[0].get("EB02AH")
                if EB02AH is None:
                    return 0
                if EB02AH in null_type_list:
                    return None
                else:
                    flag = []
                    for i in range(len(EB02AH)):
                        EB02AD01 = EB02AH[i].get("EB02AD01")   # 业务类型
                        EB02AD02 = EB02AH[i].get("EB02AD02")   # 资产质量分类
                        EB02AS04 = EB02AH[i].get("EB02AS04")   # 账户数
                        EB02AJ06 = EB02AH[i].get("EB02AJ06")   # 余额
                        if EB02AD01 is None or EB02AD02 is None or \
                                (EB02AS04 is None and EB02AJ06 is None):
                            flag.append(None)
                        else:
                            if convertDataType(EB02AD01, 'str') in ['1', '2', '3'] and \
                                    convertDataType(EB02AD02, 'str') == '3':
                                if isFloat(EB02AS04) or isFloat(EB02AJ06):
                                    EB02AS04 = convertDataType(EB02AS04, 'float')
                                    EB02AS04 = 0 if EB02AS04 is None else EB02AS04
                                    EB02AJ06 = convertDataType(EB02AJ06, 'float')
                                    EB02AJ06 = 0 if EB02AJ06 is None else EB02AJ06
                                    if EB02AJ06 > 0 or EB02AS04 > 0:
                                        Factor1 = Factor1 + 1
                            else:
                                pass
                    if len(flag) == len(EB02AH):
                        return None
                    else:
                        return Factor1
def factor2(EBC):
    # Factor2
    if EBC in null_type_list:
        return None
    elif EBC == [{}]:
        return 0
    else:
        Factor2 = 0
        #担保交易汇总信息单元  EB03 [0..1]
        EB03 = EBC[0].get("EB03")
        if EB03 is None:
            return 0
        elif EB03 in null_type_list:
            return None
        else:
            EB03A = EB03[0].get("EB03A")
            if EB03A in null_type_list:
                return None
            else:
                EB03AH = EB03A[0].get("EB03AH")
                if EB03AH is None:
                    return 0
                elif EB03AH in null_type_list:
                    return None
                else:
                    flag = []
                    for i in range(len(EB03AH)):
                        EB03AD01 = EB03AH[i].get("EB03AD01")  # 业务类型   (1银行承兑汇票or2信用证or3银行保函or9其他)
                        EB03AD02 = EB03AH[i].get("EB03AD02")  # 资产质量分类
                        EB03AS02 = EB03AH[i].get("EB03AS02")  # 账户数
                        EB03AJ01 = EB03AH[i].get("EB03AJ01")  # 余额

                        if EB03AD01 is None or EB03AD02 is None or \
                                (EB03AS02 is None and EB03AJ01 is None):
                            flag.append(None)
                        else:
                            if convertDataType(EB03AD01, 'str') in ['1', '2', '3', '9'] and \
                                    convertDataType(EB03AD02, 'str') == '3':
                                if isFloat(EB03AS02) or isFloat(EB03AJ01):
                                    EB03AS02 = convertDataType(EB03AS02, 'float')
                                    EB03AS02 = 0 if EB03AS02 is None else EB03AS02
                                    EB03AJ01 = convertDataType(EB03AJ01, 'float')
                                    EB03AJ01 = 0 if EB03AJ01 is None else EB03AJ01
                                    if EB03AJ01 > 0 or EB03AS02 > 0:
                                        Factor2 = Factor2 + 1
                            else:
                                pass
                    if len(flag) == len(EB03AH):
                        return None
                    else:
                        return Factor2

def factor3(EDA):
    # Factor3
    if EDA in null_type_list:
        return None
    elif EDA == [{}]:
        return 0
    else:
        #借贷账户信息单元  ED01  [0..*]
        ED01 = EDA[0].get("ED01")
        if ED01 is None:
            return 0
        elif ED01 in null_type_list:
            return None
        else:
            result = []
            for i in range(len(ED01)):
                ED01A = ED01[i].get("ED01A")
                ED01B = ED01[i].get("ED01B")

                if ED01A is None or ED01B is None:
                    result.append(None)
                elif ED01B == "":
                    result.append(0)
                else:
                    ED01AD01 = ED01A[0].get("ED01AD01")           # 账户活动状态
                    ED01AD02 = ED01A[0].get("ED01AD02")           # 借贷账户类型

                    if ED01AD01 in null_type_list or ED01AD02 in null_type_list:
                        result.append(None)
                    else:
                        # 还款表现信息  ED01BH  [0..*]
                        ED01BH = ED01B[0].get("ED01BH")           # 还款表现信息
                        if ED01BH is None:
                            result.append(0)
                        elif ED01BH in null_type_list:
                            result.append(None)
                        else:
                            flag = []
                            for j in range(len(ED01BH)):
                                ED01BD01 = ED01BH[j].get("ED01BD01")  # 五级分类
                                if ED01BD01 in null_type_list:
                                    flag.append(None)
                                else:
                                    if convertDataType(ED01AD01, 'str') == '1' and \
                                            convertDataType(ED01AD02, 'str') != 'D2' and \
                                            convertDataType(ED01BD01, 'str') in ['3', '4', '5', '6']:
                                        flag.append(1)
                                    else:
                                        flag.append(0)
                            flag = filter(lambda x:x is not None, flag)
                            if len(flag) == 0:
                                result.append(None)
                            else:
                                result.append(sum(flag))
            if result == []:
                return 0
            else:
                result = filter(lambda x:x is not None, result)
                if len(result) == 0:
                    return None
                else:
                    return sum(result)
def factor4(EDB):
    # Factor4
    if EDB in null_type_list:
        return None
    elif EDB == [{}]:
        return 0
    else:
        Factor4 = 0
        #担保账户信息明细单元  ED04  [0..*]
        ED04 = EDB[0].get("ED04")      # 担保账户明细
        # 不存在
        if ED04 is None:
            return 0
        # 存在 但是有问题
        elif ED04 in null_type_list:
            return None
        else:
            flag = []
            for i in range(len(ED04)):
                ED04A = ED04[i].get("ED04A")
                ED04B = ED04[i].get("ED04B")
                if ED04A in null_type_list or ED04B in null_type_list:
                    flag.append(None)
                else:
                    ED04AD01 = ED04A[0].get("ED04AD01")    # 担保账户类型
                    ED04BD01 = ED04B[0].get("ED04BD01")    # 账户活动状态
                    ED04BD02 = ED04B[0].get("ED04BD02")    # 五级分类

                    if ED04AD01 in null_type_list or ED04BD01 in null_type_list or ED04BD02 in null_type_list:
                        flag.append(None)
                    else:
                        if convertDataType(ED04AD01, 'str') in ['G1', 'G2', 'G3'] and \
                                convertDataType(ED04BD01, 'str') == '1' and \
                                convertDataType(ED04BD02, 'str') in ['3', '4', '5', '6']:
                            Factor4 = Factor4 + 1
                        else:
                            pass
            if len(flag) == len(ED04):
                return None
            else:
                return Factor4
def factor5(EBA):
    # Factor5
    if EBA in null_type_list or EBA == [{}]:
        return None
    else:
        Factor5 = 0
        EB01 = EBA[0].get("EB01")    # 信用提示单元
        if EB01 == [{}] or EB01 == "":
            return 0
        elif EB01 in null_type_list:
            return None
        else:
            # 信贷交易提示信息段  EB01A  [0..1]
            EB01A = EB01[0].get("EB01A")
            # 不存在
            if EB01A is None:
                return 0
            # 存在 但是有问题
            elif EB01A in null_type_list:
                return None
            else:
                # EB01AJ04 = EB01A[0].get("EB01AJ04")   # 不良类借贷交易余额
                EB01AJ07 = EB01A[0].get("EB01AJ07")   # 不良类担保交易余额
                if EB01AJ07 in null_type_list:
                    return None
                else:
                    if isFloat(EB01AJ07):
                        if convertDataType(EB01AJ07, 'float') > 0:
                            Factor5 = Factor5 + 1
                            return Factor5
                    else:
                        return None

def R30_EC_UpaidBusinessBadCheck():
    """
    "FACTOR1 = 统计未结清借贷交易汇总信息段(EB02A)-其他借贷交易分类汇总信息(EB02AH)·业务类型(EB02AD01)∈(1(中长期借款),2(短期借款),3(循环透支))(由于该指标剔除了“票据贴现”的业务类型，因此业务类型里不能加“合计”)且资产质量分类(EB02AD02)为“3(不良类)”的账户数(EB02AS04)或余额(EB02AJ06)＞0的记录数
    FACTOR2 = 统计未结清担保交易汇总信息段(EB03A)-未结清担保交易汇总信息(EB03AH)·业务类型(EB03AD01)∈(银行承兑汇票or信用证or银行保函or其他)且资产质量分类(EB03AD02)为“3(不良类)”的账户数(EB03AS02)或余额(EB03AJ01)＞0的记录数
    FACTOR3 = 统计借贷账户信息单元-基本信息段(ED01A)-账户活动状态(ED01AD01)为“1(未结清)”且借贷账户类型(ED01AD02)不为“D2(贴现账户)”且还款表现信息段(ED01B)-还款表现信息(ED01BH)·五级分类(ED01BD01)∈(3(次级),4(可疑),5(损失),6(违约))的记录数
    FACTOR4 = 统计担保信息单元-基本信息段(ED04A)·担保账户类型(ED04AD01)∈(G1(融资担保账户),G2(非融资担保账户),G3(支付担保账户))且在保责任信息段(ED04B)·账户活动状态(ED04BD01)为“1(未结清)”且五级分类(ED04BD02)∈(3(次级),4(可疑),5(损失),6(违约))的记录数
    FACTOR5 = 统计信贷交易提示息段(EB01A)·不良类担保交易余额(EB01AJ07)＞0的记录数
    FACTOR = MAX(FACTOR1,FACTOR2,FACTOR3,FACTOR4,FACTOR5)"

    :return:
    """


    EBB = formatData("EBB")   # 借贷交易汇总信息
    EBC = formatData("EBC")   # 担保交易汇总信息
    EDA = formatData("EDA")   # 借贷账户信息
    EDB = formatData("EDB")   # 担保账户信息
    EBA = formatData("EBA")   # 信用提示信息


    Factor1 = factor1(EBB)
    Factor2 = factor2(EBC)
    Factor3 = factor3(EDA)
    Factor4 = factor4(EDB)
    Factor5 = factor5(EBA)

    if Factor1 is None and Factor2 is None and Factor3 is None and Factor4 is None and Factor5 is None:
        return u'缺失值'
    else:
        if Factor1 is None:
            Factor1 = 0
        if Factor2 is None:
            Factor2 = 0
        if Factor3 is None:
            Factor3 = 0
        if Factor4 is None:
            Factor4 = 0
        if Factor5 is None:
            Factor5 = 0
        Factor = max(Factor5, Factor4, Factor3, Factor2, Factor1)

        return Factor

result = R30_EC_UpaidBusinessBadCheck()



